package com.yxw.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.Properties;

public class MyFactory {
    private Properties properties = new  Properties();

    public MyFactory() {
    }

    public MyFactory(String beanPropertiesPath) throws IOException {
        //这种不获取类加载器直接获取流的是直接从当前类包下取资源,得加个/才是从类路径下取
//        InputStream is = MyFactory.class.getResourceAsStream(beanPropertiesPath);


        InputStream inputStream = MyFactory.class.getClassLoader().getResourceAsStream(beanPropertiesPath);
        properties.load(inputStream);
    }

    public<T> T getBean(Class<T> tClass) throws Exception{
        //String name1 = tClass.getName();
        //获取简单类名,不用获取全类名,不然取不到properties文件的value
        String name = tClass.getSimpleName();
        String beanName = properties.getProperty(name);
        if (tClass != null) {
            Class<?> clazz = Class.forName(beanName);
            T bean = (T) clazz.getDeclaredConstructor().newInstance();
            return bean;
        }
        return null;
    }
}
